$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/user/list',
        datatype: "json",
        colModel: [			
			{ label: '用户ID', name: 'userId', index: "user_id", width: 45, key: true },
			{ label: '用户名', name: 'username', width: 75 },
			{ label: '角色名', name: 'rolename', width: 75 },
			{ label: '创建者', name: 'createname', width: 75 },
			{ label: '邮箱', name: 'email', width: 90 },
			{ label: '手机号', name: 'mobile', width: 100 },
//			{ label: '状态', name: 'userStatus', width: 80, formatter: function(value, options, row){
//				return value === 0 ? 
//					'<span class="label label-danger">禁用</span>' : 
//					'<span class="label label-success">正常</span>';
//			}},
			{ label: '状态', name: 'userStatus', width: 80, formatter: function(value, options, row){
				return value === 0 ? 
					"<a class='label label-danger' href=\"#\" onclick=\"upuserstatus(" + options.rowId +","+value+ ")\">禁用</a>" : 
					"<a class='label label-success' href=\"#\" onclick=\"upuserstatus(" + options.rowId +","+value+ ")\">正常</a>";
			}},
			{ label: '创建时间', name: 'createTime', index: "create_time", width: 80}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: false, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
function upuserstatus(id,value) {  
	var userStatus;
	if(value == 1){
		userStatus = 0;
	}else{
		userStatus = 1;
	}
	confirm('确定要更改当前状态吗？', function(){
		$.ajax({
			type: "POST",
		    url: baseURL + "sys/user/upuserstatus",
		    data: {"id":id,"userStatus":userStatus},
		    success: function(r){
				if(r.code == 0){
					alert('操作成功', function(){
						vm.reload();
					});
				}else{
					alert(r.msg);
				}
			}
		});
	});
}  
function Modify() {  
	 
	var userId = getSelectedRows();
	if(userId == null){
		return ;
	}
	console.log(userId.length) 
	if(userId.length > 1){
		alert("只能选择一条数据")
		return;
	}
	//根据当前登入用户id去查询角色 然后判断是运营角色还是普通角色从而对应显示角色列表
	$.ajax({
		type: "POST",
	    url: baseURL + "sys/role/findRoleByUserId",
        contentType: "application/json",
	    data: JSON.stringify(userId),
	    success: function(r){
	    	vm.roleList = r.list;
		}
	});
	$("#newt").modal("show");
	vm.title = "修改资料";
	vm.getUser(userId[0]);
}  
var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			username: null
		},
		showList: true,
		title:null,
		roleList:{},
		user:{
			status:1,
			roleIdList:[],
			userStatus:null,
			roleid:null
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){		
			vm.showList = false;
			vm.title = "新增";
			vm.roleList = {};
			vm.user = {status:1,roleIdList:[]};
			
			//获取角色信息
			this.getRoleList();
		},
		update: function () {
			if(!validform().form()){        		 
        		return  ;
        	} 
			var userId = getSelectedRow();
			if(userId == null){
				return ;
			}
			
			vm.showList = false;
            vm.title = "修改";
			
			vm.getUser(userId);
			//获取角色信息
			this.getRoleList();
		},
		del: function () {
			var userIds = getSelectedRows();
			if(userIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/user/delete",
                    contentType: "application/json",
				    data: JSON.stringify(userIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function () {
			if(!validform().form()){        		 
        		return  ;
        	} 
            if(vm.validator()){
                return ;
            }
            if(vm.user.userId == null){
            	var userStatus = $("input[name='status']:checked").val();
            	vm.user.userStatus = userStatus;            	
            }
//           console.log(userStatus+"a");
//            console.log(vm.user);
//            return ;
			var url = vm.user.userId == null ? "sys/user/save" : "sys/user/update";
			//console.log(vm.user);
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.user),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(){
							
							$("#newt").modal('hide');
							vm.reload();
							//location.reload();
						});
					
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getUser: function(userId){
			$.get(baseURL + "sys/user/info/"+userId, function(r){
				console.log(r.user)
				vm.user = r.user;
				vm.user.password = null;
				vm.user.roleid = r.user.roleIdList[0];
			});
		},
		getRoleList: function(){
			$.get(baseURL + "sys/role/select", function(r){
				vm.roleList = r.list;
			});
		},
		reload: function () {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
		},
        validator: function () {
            if(isBlank(vm.user.username)){
                alert("用户名不能为空");
                return true;
            }
            console.log(vm.user.username.length)
            if(vm.user.username.length >10 ){
            	alert("用户名长度不能超过10");
            	return true;
            }

            if(vm.user.userId == null && isBlank(vm.user.password)){
                alert("密码不能为空");
                return true;
            }
            if(!isBlank(vm.user.password) && vm.user.password.length >20 ){
            	alert("密码长度不能超过20");
            	return true;
            }
            if(vm.user.confirmpassword != vm.user.password){
                alert("密码和确认密码不一致");
                return true;
            }

            if(isBlank(vm.user.email)){
                alert("邮箱不能为空");
                return true;
            }

            if(!validator.isEmail(vm.user.email)){
                alert("邮箱格式不正确");
                return true;
			}
            var rel = /^1[3|4|5|7|8][0-9]\d{8}$/; 
            if(!rel.test(vm.user.mobile)) 
            { 
                alert('请输入有效的手机号码！'); 
                return true; 
            } 
            
            if(isBlank(vm.user.roleid)){
                alert("角色不能为空");
                return true;
            }
        }
	}
});